package com.itheima.ydd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.ydd.common.R;
import com.itheima.ydd.dto.PageInfo;
import com.itheima.ydd.mapper.YddUserMapper;
import com.itheima.ydd.pojo.SysUser;
import com.itheima.ydd.pojo.YddUser;
import com.itheima.ydd.service.SysUserService;
import com.itheima.ydd.service.YddUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

//用户管理
@Service
public class YddUserServiceImpl extends ServiceImpl<YddUserMapper, YddUser> implements YddUserService {

    @Autowired
    private SysUserService sysUserService;
    //添加用户
    @Override
    public ResponseEntity<R<String>> addYddUser(YddUser yddUser) {


        save(yddUser);
        return ResponseEntity.ok(R.success("添加成功"));
    }

    //删除用户
    @Override
    public ResponseEntity<R<String>> delYddUser(Integer id) {
        removeById(id);
        return ResponseEntity.ok(R.success(null));
    }

    @Override
    public ResponseEntity<R<String>> updateYddUser(YddUser yddUser) {
        SysUser sysUser = sysUserService.getById(yddUser.getId());
        boolean flag = false;
        if (StringUtils.pathEquals(yddUser.getPassword(), sysUser.getPassword())) {
            flag = true;
        }//密码未修改
//走else说明密码已修改,对新密码进行加密,并设置
        else {
            yddUser.setPassword(DigestUtils.md5DigestAsHex(yddUser.getPassword().getBytes()));
        }
        updateById(yddUser);
        return flag ? ResponseEntity.ok(R.success("修改成功")) : ResponseEntity.ok(R.success("修改成功,密码已修改"));

    }

    //分页
    @Override
    public ResponseEntity<R<PageInfo<YddUser>>> findPage(Integer page, Integer limit, String sex, String username, String mobile) {
        IPage<YddUser> pg=new Page<YddUser>(page,limit);

        LambdaQueryWrapper<YddUser> wrapper=new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.hasText(sex),YddUser::getSex,sex);
        wrapper.like(StringUtils.hasText(username),YddUser::getUsername,username);
        wrapper.like(StringUtils.hasText(mobile),YddUser::getMobile,mobile);
        wrapper.orderByAsc(YddUser::getId);
        page(pg,wrapper);
        PageInfo<YddUser> pageInfo = new PageInfo<>();
        //将数据封装到pageinfo新对象中
        pageInfo.setCount((int) pg.getTotal());
        pageInfo.setTotalPages((int) pg.getPages());
        pageInfo.setPageSize((int) pg.getSize());
        pageInfo.setCurrentPage((int) pg.getCurrent());
        pageInfo.setData(pg.getRecords());
        return ResponseEntity.ok(R.success(pageInfo));
    }
}
